package com.woniu.woniu_bx.filter;

import com.woniu.woniu_bx.exception.ValidCaptchaException;
import com.woniu.woniu_bx.pojo.Manager;
import com.woniu.woniu_bx.pojo.Perm;
import com.woniu.woniu_bx.pojo.Role;
import com.woniu.woniu_bx.service.ManagerService;
import com.woniu.woniu_bx.service.RoleService;
import com.woniu.woniu_bx.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author leonie
 * @Date 2022/8/23 14:39
 */
public class JwtVarifyProvider implements AuthenticationProvider {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private RoleService roleService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authentication;
        //解析token
        String token = (String) jwtToken.getPrincipal();
        if (token!=null){
            int id = jwtUtil.getID(token);
            Manager manager = managerService.getById(id);
            Role role = roleService.getRoleByID(manager.getRoleId());
            List<SimpleGrantedAuthority> list = new ArrayList<>();
            for (Perm perm : role.getPermList()) {
                list.add(new SimpleGrantedAuthority(perm.getCode()));
            }
            //产生已认证的JwtToken
            JwtToken authenticatedToken = new JwtToken(token, true, list);
            //保存起来
            SecurityContextHolder.getContext().setAuthentication(authenticatedToken);
//            JwtToken authToken = new JwtToken(token,true,list);
//            SecurityContextHolder.getContext().setAuthentication(authToken);
            return authenticatedToken;
        }else {
            throw new ValidCaptchaException("token失效");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtToken.class.isAssignableFrom(authentication);
    }
}
